//
//  FootPrintViewModel.swift
//  Pods
//
//  Created by eme on 2017/3/31.
//
//

import RxSwift
import SwiftyJSON
import NetWorkCore
import ModelProtocol
import UtilCore
import Result
/**
 足迹列表ViewModel
 */
class FootPrintViewModel:Base_Vm{
    
    let getFootPrintList = PublishSubject<String>()
    let footListModel = PublishSubject<[FootPrintModel]>()
    let refreshing = Variable(false)
    let deleteFootPrint = PublishSubject<String>()
    let deleteBackData = PublishSubject<[FootPrintModel]>()
    let loading : Observable<Bool>
    
    override init(){
        
        let requestIndicator = ActivityIndicator()
        self.loading = requestIndicator.asObservable()
        
        super.init()

        let request = Observable
            .of(
                getFootPrintList.asObserver()
                ,reloadTrigger.withLatestFrom(getFootPrintList.asObserver()))
            .merge()
            .map{ _ in
                return MineApi.getFootPrintList(page:0,length: 0)
            }.shareReplay(1)
        
        let response = request.emeRequestApiForArray(FootPrintModel.self, activityIndicator: requestIndicator).shareReplay(1)
        
        response.subscribe(onNext:{ [unowned self] result in
            switch result{
            case .success(let data):
                self.footListModel.onNext(data)
            case .failure(let error):
                self.refresherror.onNext(error)
            }
        }).addDisposableTo(disposeBag)
        
        let deleteRequest = deleteFootPrint.map{ fid in
            
            return MineApi.deleteFootPrint(fid: fid)
            
            }.shareReplay(1)
        
        let deleteResponse = deleteRequest.emeRequestApiForArray(FootPrintModel.self).shareReplay(1)
        
        deleteResponse.subscribe(onNext:{[unowned self] result in
            switch result{
            case.success(let data):
                self.deleteBackData.onNext(data)
            case .failure(let error):
                self.error.onNext(error)
            }
        }).addDisposableTo(disposeBag)
    }
    
}
